package gii

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"store/libs/helper"
	"store/models/base"
	"strings"
)

func Start(router *gin.Engine, db *gorm.DB) {
	router.GET("/gii/gen-code", GenCode)
}

func GenCode(ctx *gin.Context) {
	model := base.NewCommonModel(ctx)
	tables := model.AllTables()

	tableBuf := bytes.NewBufferString("")
	if len(tables) > 0 {
		for _, table := range tables {
			tableBuf.Write(renderTableList(table))
		}
	}

	tableName := ctx.Query("table")

	fieldList := map[string]base.Field{}
	if tableName != "" {
		if model.TableExists(tableName) {
			tableInfo := model.TableInfo(tableName)
			fieldList = base.AnalysisTable(tableInfo)
		}
	}

	property := renderProperty4Md(fieldList)
	map2Model := renderMap2Model4Md(fieldList)
	input := renderInput4Md(fieldList)
	info2Input := renderInfo2Input4Md(fieldList)

	code := render([]byte(mdT), tableBuf, tableName, property, map2Model, input, info2Input)
	helper.RenderHtml(ctx, http.StatusOK, code)
}

func render(template []byte, tableBuf *bytes.Buffer, table string, property []byte, map2Model []byte, input []byte, info2Input []byte) []byte {
	template = bytes.Replace(template, []byte("{{tableList}}"), tableBuf.Bytes(), -1)
	template = bytes.Replace(template, []byte("{{table}}"), []byte(table), -1)
	template = bytes.Replace(template, []byte("{{TABLE}}"), []byte(strings.ToUpper(table)), -1)
	template = bytes.Replace(template, []byte("{{Struct}}"), []byte(helper.Line2BigCase(table, "_")), -1)
	template = bytes.Replace(template, []byte("{{struct-route}}"), []byte(strings.Replace(table, "_", "-", -1)), -1)
	template = bytes.Replace(template, []byte("{{Properties}}"), property, -1)
	template = bytes.Replace(template, []byte("{{map2ModelProperties}}"), map2Model, -1)
	template = bytes.Replace(template, []byte("{{inputProperties}}"), input, -1)
	template = bytes.Replace(template, []byte("{{info2InputProperties}}"), info2Input, -1)
	return template
}
